package com.epic.quartz.service;

import com.epic.inter.IJobManager;
import com.epic.po.quartz.TaskInfo;
import com.epic.quartz.BaseTask;
import org.apache.dubbo.config.annotation.DubboService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

@DubboService(version = "1.0.0")
public class IJobManagerImpl implements IJobManager {

    private static Logger logger =  LoggerFactory.getLogger(IJobManagerImpl.class);

    @Resource(name = "schedulerFactoryBean")
    private Scheduler scheduler;

    @Override
    public void addJob(TaskInfo taskInfo) {
        TriggerKey triggerKey =  TriggerKey.triggerKey(taskInfo.getTaskDesc(),taskInfo.getTaskBean());
        try{
            Trigger trigger = scheduler.getTrigger(triggerKey);
            JobDetail jobDetail = JobBuilder.newJob(BaseTask.class)
                    .withDescription(taskInfo.getTaskDesc())
                    .withIdentity(taskInfo.getTaskBean(),taskInfo.getTaskDesc()).build();
            //从传递的参数中获取到对应的信息
            jobDetail.getJobDataMap().put("taskInfo", taskInfo);
            logger.info("111");
            scheduler.addJob(jobDetail,true,true);
            if (taskInfo.getRunMode() == 1){
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(taskInfo.getScheduleParam());
                logger.info("110");
                JobKey jobKey = JobKey.jobKey(taskInfo.getTaskDesc(),taskInfo.getTaskBean());
                logger.info("112");
                if (trigger != null) {
                    //按新的cronExpression表达式重新构建trigger
                    trigger = ((CronTrigger) trigger).getTriggerBuilder().withIdentity(triggerKey).forJob(jobKey)
                            .withSchedule(cronScheduleBuilder).build();
                    logger.info("113");
                    scheduler.rescheduleJob(triggerKey,trigger);
//                    scheduler.start();
                } else {
                    logger.info("114");
                    trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).forJob(jobKey)
                            .withSchedule(cronScheduleBuilder).build();
//                    scheduler.scheduleJob(jobDetail,trigger);
                    scheduler.scheduleJob(trigger);
                    logger.info("115");
//                    scheduler.start();
                }
            }
            logger.info("add job ok " + taskInfo.getTaskBean());
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @Override
    public String test() {
        logger.info("enter quartz service");
        return "ok";
    }
}
